import React, { useEffect, useMemo, useState } from 'react';

import { Checkbox, Col, Form, Input, InputNumber, Radio, Row, Select } from 'antd';
import {
  DatePickerFormatsLocale,
  DEFAULT_CACHE_EXPIRED,
  FilterTypeList,
  FilterTypes,
  FilterTypesLocale,
} from '../constants';
import { IGlobalControl, InteractionType } from '../types';
import { getDatePickerFormatOptions, getOperatorOptions } from '../util';
import styles from '../index.less';

const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;

require('@/assets/less/util.less');

interface IFilterFormBaseProps {
  form: any
  selected: IGlobalControl
  interactionType: InteractionType
}


type IFilterFormProps = IFilterFormBaseProps

interface IFieldForm {
  key: string
  type?: string
  multiple?: boolean
  cache?: boolean
  expired?: number
  dynamicDefaultValue?: any
  operator?: any
  dateFormat?: any
}

const initFieldVal: IFieldForm = {
  key: '',
  type: FilterTypes.Select,
  multiple: false,
  cache: false,
  expired: DEFAULT_CACHE_EXPIRED,
  dynamicDefaultValue: '',
};

const FilterForm: React.FC<IFilterFormProps> = (props: IFilterFormProps) => {
  const [fieldVals, setFieldVals] = useState(initFieldVal);
  let { interactionType, selected, form } = props;
  const fields = Object.entries(fieldVals).reduce<Array<{ name: string, value: any }>>((field, [k, v]) => {
    field.push({ name: k, value: v });
    return field;
  }, []);
  useEffect(() => {
    const { key, type, multiple, cache, expired, dynamicDefaultValue } = selected;
    setFieldVals({ ...fields, key, type, multiple, cache, expired, dynamicDefaultValue });
  }, [selected]);
  const { type, multiple, dynamicDefaultValue } = fieldVals;
  const datePickerFormatOptions = getDatePickerFormatOptions(type, multiple);
  const operatorOptions: any[] = getOperatorOptions(type, multiple);
  useMemo(() => {
    if (fieldVals.type === FilterTypes.Select) {
      setFieldVals({ ...fieldVals, operator: operatorOptions[0] });
    } else if (fieldVals.type === FilterTypes.DateRange) {
      setFieldVals({ ...fieldVals, dateFormat: datePickerFormatOptions[0] });
    }

  }, [fieldVals.type, fieldVals.multiple]);

  const renderDefaultValueComponent = () => {
    let container = (
      <>
        <Col span={8}>
          <FormItem label='默认值' name='dynamicDefaultValue'>
            <Input size='small' value={dynamicDefaultValue} />
          </FormItem>
        </Col>
      </>
    );
    return container;
  };

  const filterTypeRelatedInput = [];

  const dateFormatFormComponent = (
    <Col key='dateFormat' span={8}>
      <FormItem label='日期格式' name='dateFormat'>
        <Select size='small'>
          {
            datePickerFormatOptions.map((format) => {
              const title = DatePickerFormatsLocale[format];
              return (
                <Option key={title} value={format}>{title}</Option>
              );
            })
          }
        </Select>
      </FormItem>
    </Col>
  );

  const multipleFormComponent = (
    <Col key='multiple' span={8}>
      <FormItem label='功能' name='multiple' valuePropName='checked'>
        <Checkbox>多选</Checkbox>
      </FormItem>
    </Col>
  );

  switch (type) {
    case FilterTypes.DateRange:
      filterTypeRelatedInput.push(dateFormatFormComponent);
      break;
    case FilterTypes.Select:
      filterTypeRelatedInput.push(multipleFormComponent);
      break;
    default:
      break;
  }
  const onFieldsChange = (changedFields: any, allFields: any[]) => {
    const fieldVal: IFieldForm = allFields.reduce<IFieldForm>((fieldVal, field) => {
      fieldVal[field.name[0]] = field.value;
      return fieldVal;
    }, {} as IFieldForm);
    setFieldVals({ ...fieldVal });
  };
  return (
    <Form className={styles.filterForm} form={form} fields={fields} layout='vertical' onFieldsChange={onFieldsChange}>
      <div className={styles.title}>
        <h2>控制器配置</h2>
      </div>
      <Row gutter={8} className={styles.formBody}>
        <Col span={8}>
          <FormItem className={styles.hide} name='key'>
            <Input />
          </FormItem>
          <FormItem label='类型' name='type'>
            <Select size='small'>
              {
                FilterTypeList.map((filterType) => (
                  <Option key={filterType} value={filterType}>{FilterTypesLocale[filterType]}</Option>
                ))
              }
            </Select>
          </FormItem>
        </Col>
        {filterTypeRelatedInput}
      </Row>
      <Row gutter={8} className={styles.formBody}>
        {
          interactionType === 'column'
          && operatorOptions
          && !!operatorOptions.length && (
            <Col span={8}>
              <FormItem label='对应关系' name='operator'>
                <Select size='small'>
                  {
                    operatorOptions.map((o) => (
                      <Option key={o} value={o}>{o}</Option>
                    ))
                  }
                </Select>
              </FormItem>
            </Col>
          )
        }
        {
          type === FilterTypes.Select && (
            <>
              <Col key='cache' span={6}>
                <FormItem label='缓存' name='cache'>
                  <RadioGroup size='small'>
                    <RadioButton value>开启</RadioButton>
                    <RadioButton value={false}>关闭</RadioButton>
                  </RadioGroup>
                </FormItem>
              </Col>
              <Col key='expired' span={8}>
                <FormItem label='有效期（秒）' name='expired'>
                  <InputNumber size='small' />
                </FormItem>
              </Col>
            </>
          )
        }
      </Row>
      <Row gutter={8} className={styles.formBody}>
        {/*{renderDefaultValueComponent()}*/}
      </Row>
    </Form>
  );
};
export default FilterForm;
